<template>
  <div>
    <el-dialog
      :title="info.type === 'add' ? '新增商品' : '编辑商品'"
      :visible.sync="info.isShow"
      width="60%"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="一级分类" prop="first_cateid">
              <el-select v-model="ruleForm.first_cateid" @change="firstChange">
                <el-option label="请选择" :value="0"></el-option>
                <el-option
                  v-for="(item, index) in firstList"
                  :key="index"
                  :label="item.catename"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级分类" prop="second_cateid">
              <el-select v-model="ruleForm.second_cateid">
                <el-option label="请选择" :value="0"></el-option>
                <el-option
                  v-for="(item, index) in secondList"
                  :key="index"
                  :label="item.catename"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品名称" prop="goodsname">
              <el-input v-model="ruleForm.goodsname"></el-input>
            </el-form-item>
            <el-form-item label="市场价格" prop="market_price">
              <el-input v-model="ruleForm.market_price"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="ruleForm.price"></el-input>
            </el-form-item>
            <el-form-item label="商品图片">
              <el-upload
                action="#"
                :auto-upload="false"
                list-type="picture-card"
                :on-remove="handleRemove"
                :on-change="handleChange"
                :file-list="fileList"
                :limit="1"
                :on-exceed="handlerExceed"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="商品规格" prop="specsid">
              <el-select v-model="ruleForm.specsid" @change="specsChange">
                <el-option label="请选择" :value="0"></el-option>
                <el-option
                  v-for="(item, index) in specsList"
                  :key="index"
                  :label="item.specsname"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="规格属性值" prop="specsattr">
              <el-select v-model="ruleForm.specsattr" multiple>
                <el-option label="请选择" :value="0"></el-option>
                <el-option
                  v-for="(item, index) in attrList"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否新品" prop="isnew">
              <el-radio-group v-model="ruleForm.isnew">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否热卖" prop="ishot">
              <el-radio-group v-model="ruleForm.ishot">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="ruleForm.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="2">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="详细描述" name="second">
          <div id="div1"></div>
        </el-tab-pane>
      </el-tabs>
      <el-button
        v-if="info.type === 'add'"
        type="primary"
        @click="submitForm('ruleForm')"
        >立即创建</el-button
      >
      <el-button v-else type="success" @click="submitForm('ruleForm')"
        >立即修改</el-button
      >
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-dialog>
  </div>
</template>

<script>
// 富文本编辑器
import E from 'wangeditor'
import { menuEdit, cateList, getInfoByPid, goodsAdd, specstList, getSpecsinfo, goodsEdit } from "../../api";
export default {
  props: ["info"],
  data() {
    return {
      // tabs标签页激活的选项
      activeName: "first",
      // 一级分类的下拉菜单
      firstList: [],
      // 二级分类的下拉菜单
      secondList: [],
      // 商品规格的下拉菜单
      specsList: [],
      // 商品规格属性值的下拉菜单
      attrList: [],
      // 历史图片列表
      fileList: [],
      // 角色列表
      roleList: [],
      ruleForm: {
        first_cateid: 0,
        second_cateid: 0,
        goodsname: "",
        market_price: 1,
        price: 1,
        description: "",
        img: "",
        specsid: 0,
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      },
      rules: {
        title: [{ required: true, message: "请输入菜单标题", trigger: "blur" }],
      },
      // 编辑器
      editor: null
    };
  },
  created() {
    // 获取一级分类下拉数据
    this.getFirstList();
    // 获取规格列表
    this.getSpecstList();
    // 如果是编辑，还需要额外发请求获取二级分类和规格属性值的下拉数据
  },
  methods: {
    // 给表单赋值
    setValue(info) {
      // 深拷贝，比避免数据互相影响
      this.ruleForm = { ...info };
      // 等待dom加载完成
      this.$nextTick(()=>{
        if(!this.editor) {
          // 打开弹出时初始化编辑器,且不能重发创建
          this.editor = new E('#div1');
          this.editor.create()
        }
        // 编辑时要将原数据填入编辑器
        this.editor.txt.html(this.ruleForm.description)
      })
    },
    async getFirstList() {
      let res = await cateList();
      this.firstList = res.list;
    },
    async getSpecstList() {
      let res = await specstList();
      this.specsList = res.list;
    },
    // 一级分类改变，需要获取对应的二级数据，每次都要获取
    async firstChange() {
      this.ruleForm.second_cateid = 0;
      // 这个方法可以少发请求，提高速度
      // this.firstList.forEach(item => {
      //     if(item.id === this.ruleForm.first_cateid) {
      //       this.secondList.push(item.children)
      //   }
      // })
      // 这个方法，简单
      let res = await getInfoByPid(this.ruleForm.first_cateid);
      this.secondList = res.list;
    },
    // 规格属性变化，属性值也要一起变
    async specsChange() {
      let res = await getSpecsinfo(this.ruleForm.specsid);
      this.attrList = res.list[0].attrs;
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.ruleForm.specsattr = this.ruleForm.specsattr.join(',')
          this.ruleForm.description = this.editor.txt.html();
          // 删除多余字段，避免报错
          this.ruleForm.firstcatename ? delete this.ruleForm.firstcatename: ''
          this.ruleForm.secondcatename ? delete this.ruleForm.secondcatename: ''
          let fd = new FormData();
          for (const key in this.ruleForm) {
            // append是增加数据的方法
            fd.append(key, this.ruleForm[key]);
          }
          if (this.info.type === "add") {
            let res = await goodsAdd(fd);
            console.log(res);
          } else {
            // 编辑
            let res = await goodsEdit(fd);
          }
          // 关闭弹窗
          this.info.isShow = false;
          // 通知list再次获取数据  info->index->list
          this.$emit("update");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除图片
    handleRemove() {
      this.ruleForm.img = "";
    },
    // 修改文件
    handleChange(file) {
      this.ruleForm.img = file.raw;
    },
    // 文件超出个数限制时的钩子
    handlerExceed() {
      this.$message({
        type: "warning",
        message: "最多上传一张图片",
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
</style>